package com.ed.controller;

import cn.hutool.core.util.ObjUtil;
import com.ed.domain.User;
import com.ed.dto.EditUserDTO;
import com.ed.dto.UserPageByConditionDTO;
import com.ed.dto.UserRegisterDTO;
import com.ed.exception.BaseException;
import com.ed.result.PageResult;
import com.ed.result.Result;
import com.ed.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Slf4j
@RequiredArgsConstructor
@CrossOrigin
public class UserController {
	
	private final UserService userService;
	
	@PostMapping("/test")
	public Result<String> test() {
		return Result.success("test");
	}
	
	/**
	 * 登录
	 *
	 * @param user
	 * @return
	 */
	@PostMapping("/login")
	public Result<String> login(@RequestBody User user) {
		if (ObjUtil.isEmpty(user)) {
			throw new BaseException("参数为空");
		}
		return Result.success(userService.login(user));
	}
	
	/**
	 * 管理员登录
	 *
	 * @param user
	 * @return
	 */
	@PostMapping("/loginAdmin")
	public Result<String> loginAdmin(@RequestBody User user) {
		if (ObjUtil.isEmpty(user)) {
			throw new BaseException("参数为空");
		}
		return Result.success(userService.loginAdmin(user));
	}
	
	/**
	 * 短信登录
	 */
	@PostMapping("/loginMessage")
	public Result<String> loginMessage(@RequestBody User user) {
		if (ObjUtil.isEmpty(user)) {
			throw new BaseException("参数为空");
		}
		return Result.success(userService.loginMessage(user));
	}
	
	/**
	 * 注册
	 *
	 * @param userRegisterDTO
	 * @return
	 */
	@PostMapping("/register")
	public Result register(@RequestBody UserRegisterDTO userRegisterDTO) {
		if (ObjUtil.isEmpty(userRegisterDTO)) {
			throw new BaseException("参数为空");
		}
		userService.register(userRegisterDTO);
		return Result.success();
	}
	
	/**
	 * 编辑用户信息
	 *
	 * @param userDto
	 * @return
	 */
	@PutMapping("/admin/update")
	public Result<String> updateUserInfo(@RequestBody EditUserDTO userDto) {
		log.info("修改用户信息,被修改后的信息为{}", userDto);
		userService.updateUserInfo(userDto);
		return Result.success();
	}
	
	/**
	 * 管理员分页查询用户信息
	 * 参数：手机号 or 姓名
	 *
	 * @return id、真实姓名、手机号、住院号
	 */
	@GetMapping("/admin/pageUserByCondition")
	public Result<PageResult> pageByCondition(UserPageByConditionDTO userPageByConditionDTO) {
		return Result.success(userService.pageByCondition(userPageByConditionDTO));
	}
	
	/**
	 * 管理员新增用户
	 *
	 * @return
	 */
	@PostMapping("/admin/addUser")
	public Result addUser(@RequestBody UserRegisterDTO userRegisterDTO) {
		userService.register(userRegisterDTO);
		return Result.success();
	}
	
	/**
	 * 管理员删除用户
	 *
	 * @return
	 */
	@PostMapping("/admin/deleteUser")
	public Result deleteUser(@RequestParam("id") Integer id) {
		userService.deleteUser(id);
		return Result.success();
	}
}
